package xyz.jcat.spring.security.example;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //TODO 查询数据库
        UserDetails userDetails = null;
        if(Objects.equals(username, "zs")) {
            Collection<RoleGrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new RoleGrantedAuthority(1L));
            authorities.add(new RoleGrantedAuthority(5L));

            userDetails = new User(
                    username,
                    "$2a$10$Yr3VjJcMFOAtbw.SmYmT0.kXJEPmujXPz9PgttzkftJtlzqioZYlq",
                    true, //是否启用
                    true, //是否过期
                    true, //凭证是否过期
                    true, // 是否锁定
                    authorities);
        }
        if(Objects.isNull(userDetails)) {
            throw new UsernameNotFoundException("用户名错误："+username);
        }
        return userDetails;
    }

}
